package com.piao.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

//SqlSessionFactory获取SqlSession
public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

    //静态代码块，初始时就执行
    static {
        try {
            //从配置文件读取配置，获取SqlSession对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //从SqlSessionFactory获取SqlSession连接
    public static SqlSession getSession(){

        return sqlSessionFactory.openSession();
        //return sqlSessionFactory.openSession(true);//自动提交事务
    }

}